﻿using Abp.Application.Services.Dto;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using Camc.Quality.Authorization.Users;
using Camc.Quality.DataDictionary;
using Camc.Quality.Dto;
using Camc.Quality.QualityPlatform;
using Camc.Quality.Tooling.Dto;
using Camc.Quality.Tooling.ToolingInterface;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using static Camc.Quality.Tooling.ToolEnum;

namespace Camc.Quality.Tooling
{
    public class ToolingAppService : QualityAppServiceBase
    {
        private readonly IRepository<ToolingDesc, Guid> _toolingDescRepostory;
        private readonly IRepository<ToolingNode, Guid> _toolingNodeRepostory;
        private readonly IRepository<ToolingContent, Guid> _toolingContentRepostory;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        private readonly IToolingsExprotToExcel _toolingsExprotToExcel;
        private readonly IToolingsImportToTable _toolingsImportToTable = new ToolingsImportToTable();
        public ToolingAppService(IRepository<ToolingDesc, Guid> toolingDescRepostory, IRepository<ToolingNode, Guid> toolingNodeRepostory, IRepository<ToolingContent, Guid> toolingContentRepostory, IToolingsExprotToExcel toolingsExprotToExcel)
        {
            this._toolingContentRepostory = toolingContentRepostory;
            this._toolingDescRepostory = toolingDescRepostory;
            this._toolingNodeRepostory = toolingNodeRepostory;
            this._toolingsExprotToExcel = toolingsExprotToExcel;
        }
        /// <summary>
        /// 工装树树加载
        /// </summary>
        /// <returns></returns>
        public List<ToolingNodeDto> GetTreeGrid(Guid ParentId)
        {
            List<ToolingNodeDto> treeClassDtos = null;
            var toolingNodes = _toolingNodeRepostory.GetAll().Where(t => t.ParentCode == ParentId).ToList();
            if (toolingNodes != null)
            {
                if (toolingNodes != null && toolingNodes.Count > 0)
                {
                    foreach (var item in toolingNodes)
                    {
                        ToolingNodeDto treeClassDto = new ToolingNodeDto
                        {
                            Id = item.Id,
                            HasChild = item.HasChild,
                            ToolingTypeName = item.ToolingTypeName,
                            OrderNum = item.OrderNum,
                            ParentCode = item.ParentCode,
                            LevelNum = item.LevelNum,
                            ToolingTypeCode = item.ToolingTypeCode
                        };
                        treeClassDtos.Add(treeClassDto);
                    }
                }
                return treeClassDtos;
            }
            return treeClassDtos;
        }

        /// <summary>
        /// 节点新增和修改接口，根据是否传输id判断
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreateOrUpdateToolingNode(ToolingNodeDto toolingNodeDto)
        {
            if (toolingNodeDto.Id == Guid.Empty)
            {
                await CreateToolingNode(toolingNodeDto);
            }
            else
            {
                await UpdateToolingNode(toolingNodeDto);
            }
        }
        /// <summary>
        /// 增加节点
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task CreateToolingNode(ToolingNodeDto toolingNodeDto)
        {
            //查找是否有父级数据
            var materiaParentNode = _toolingNodeRepostory.GetAll().Where(t => t.Id == toolingNodeDto.ParentCode);
            if (materiaParentNode.Count() > 0)
            { // 根据parentCode 找到 父级 根据id 更新父级的HasChild 
                var materiaParentNodeResult = _toolingNodeRepostory.FirstOrDefaultAsync(t => t.Id == toolingNodeDto.ParentCode).Result;
                if (materiaParentNodeResult.Id != Guid.Empty)
                {
                    materiaParentNodeResult.HasChild = true;
                    await _toolingNodeRepostory.UpdateAsync(materiaParentNodeResult);
                }
                //找出当前父节点下有几条数据 如果大于0 说明有子级 新增时 总条数加一
                int toolingNodeCount = _toolingNodeRepostory.Count(t => t.ParentCode == toolingNodeDto.ParentCode);
                //if (materialNodeCount == 0)
                //{
                //    materialsNodeEditDto.MaterialTypeCode = materialsNodeEditDto.MaterialTypeCode + '_' + (materialNodeCount);
                //}
                //else
                //{
                toolingNodeDto.ToolingTypeCode = toolingNodeDto.ToolingTypeCode + '_' + (toolingNodeCount + 1);
                // }
            }

            //var materiaChildNode = _materialsNodeRepository.GetAll().Where(t => t.ParentCode.Equals(materiaParentNode.Id)).ToList();
            ////降序取最大序号
            //materiaChildNode = materiaChildNode.OrderByDescending(o => o.LevelNum).ToList();
            // int levelNum = materiaChildNode[0].LevelNum;
            ToolingNode toolingNodes = new ToolingNode()
            {
                ToolingDescId = toolingNodeDto.ToolingDescId,
                ToolingTypeName = toolingNodeDto.ToolingTypeName,
                ParentCode = toolingNodeDto.ParentCode,
                HasChild = toolingNodeDto.HasChild,
                LevelNum = toolingNodeDto.LevelNum + 1,
                ToolingTypeCode = toolingNodeDto.ToolingTypeCode,
                Id = Guid.NewGuid()
            };
            //如果没有父级 那就已当前id作为code
            if (materiaParentNode.Count() == 0)
            {
                if (string.IsNullOrEmpty(toolingNodeDto.ToolingTypeCode))
                {
                    toolingNodeDto.ToolingTypeCode = "";
                }
                toolingNodes.ToolingTypeCode = toolingNodes.Id.ToString();
            }
            await _toolingNodeRepostory.InsertAsync(toolingNodes);
        }
        /// <summary>
        /// 更新节点
        /// </summary>
        /// <param name="toolingNodeDto"></param>
        /// <returns></returns>
        private async Task UpdateToolingNode(ToolingNodeDto toolingNodeDto)
        {
            var toolingNodeData = await _toolingNodeRepostory.FirstOrDefaultAsync(t => t.Id == toolingNodeDto.Id);
            if (toolingNodeData != null)
            {
                toolingNodeData.ToolingTypeName = toolingNodeDto.ToolingTypeName;
            }
            await _toolingNodeRepostory.UpdateAsync(toolingNodeData);
        }

        /// <summary>
        /// 删除工装树节点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteNode(Guid id)
        {
            var toolingChildNode = _toolingNodeRepostory.FirstOrDefaultAsync(b => b.Id == id).Result;
            if (toolingChildNode != null)
            {
                int childNodeCount = await _toolingNodeRepostory.CountAsync(t => t.ParentCode == id);
                if (childNodeCount == 0)
                {
                    //判断附表有没有对应数据
                    int toolingContentCount = await _toolingContentRepostory.CountAsync(t => t.ToolingNodeId == toolingChildNode.Id);
                    if (toolingContentCount > 0)
                    {
                        throw new UserFriendlyException("该节点下存在有效数据,请先删除");
                    }
                    else
                    {
                        await _toolingNodeRepostory.DeleteAsync(t => t.Id == id && t.ToolingTypeName.StartsWith(toolingChildNode.ToolingTypeName));
                    }
                }
                else
                {
                    throw new UserFriendlyException("该节点下存在子节点,请先删除子节点");

                }
            }
            else
            {
                throw new UserFriendlyException("该节点异常,请重试或联系管理员");
            }
        }

        /// <summary>
        /// 根据节点获取工装详细信息
        /// </summary>
        /// <param name="typeId"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<ToolingContentDto>> GetmaterialsContentByNode(GetToolingContentListPageDto input
            )
        {
            var userData = _userRepository.GetAll().ToList();
            var query = from toolingContent in _toolingContentRepostory.GetAll().
                        WhereIf(!input.ToolingNodeId.Equals(Guid.Empty), x => x.ToolingTypeCode.StartsWith(input.ToolingTypeCode))
                        join toolingNode in _toolingNodeRepostory.GetAll() on toolingContent.ToolingNodeId equals toolingNode.Id
                        join code in _sysCodeRepository.GetAll().Where(t => t.CodeId == "10") on toolingContent.UnitId equals code.Id
                        into codeData
                        from cd in codeData.DefaultIfEmpty()
                        join codeTool in _sysCodeRepository.GetAll().Where(t => t.CodeId == "11") on toolingContent.LifeStateId equals codeTool.Id
                        into codeToolData
                        from cdtd in codeToolData.DefaultIfEmpty()
                        join codeUser in _sysCodeRepository.GetAll().Where(t => t.CodeId == "12") on toolingContent.KeeperId equals codeUser.Id
                        into codeUserData
                        from cdud in codeUserData.DefaultIfEmpty()
                        join codeLevel in _sysCodeRepository.GetAll().Where(t => t.CodeId == "13") on toolingContent.LevelNo equals codeLevel.Id
                        into codeLevelData
                        from cdld in codeLevelData.DefaultIfEmpty()
                        join users in userData on toolingContent.CreatorUserId equals users.Id
                        select new ToolingContentDto
                        {
                            Id = toolingContent.Id,
                            ToolingName = toolingContent.ToolingName,
                            ToolingNo = toolingContent.ToolingNo,
                            ToolingTypeName = toolingNode.ToolingTypeName,
                            UnitId = cd.Id,
                            Unit = cd.Code,
                            ToolIsUseState = EnumTransfer.GetEnumName<ToolingIsUseState>((int)toolingContent.ToolIsUseStateEnum),
                            Modle = toolingContent.Modle,
                            LifeStateId = cdtd.Id,
                            LifeStateName = cdtd.Code,
                            Remark = toolingContent.Remark,
                            KeeperId = cdud.Id,
                            KeeperName = cdud.Code,
                            LevelNo = cdld.Code,
                            DrawingNo = toolingContent.DrawingNo
                        };
            if (query != null)
            {
                try
                {
                    var toolingContentDataList = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
                    return new PagedResultDto<ToolingContentDto>(query.Count(), toolingContentDataList);
                }
                catch (Exception ex)
                {
                    throw new UserFriendlyException("系统内部错误,请重试或联系管理员");
                }
            }
            else
            {
                throw new UserFriendlyException("异常,请重试或联系管理员");
            }
        }
        /// <summary>
        /// 根据过滤条件获取工装信息
        /// </summary> 
        /// <param name="typeId"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<ToolingContentDto>> GetmaterialsContentByFilter(GetToolingContentListPageDto input
       )
        {
            var userData = _userRepository.GetAll().ToList();
            var query = from toolingContent in _toolingContentRepostory.GetAll().
                         WhereIf(!input.ToolingNodeId.Equals(Guid.Empty), x => x.ToolingTypeCode.StartsWith(input.ToolingTypeCode))
                        .WhereIf(!input.ToolingNo.IsNullOrWhiteSpace(), x => x.ToolingNo.Contains(input.ToolingNo))
                        .WhereIf(!input.ToolIsUseState.ToString().IsNullOrWhiteSpace(), x => x.ToolIsUseStateEnum == (ToolingIsUseState)input.ToolIsUseState)
                        join toolingNode in _toolingNodeRepostory.GetAll() on toolingContent.ToolingNodeId equals toolingNode.Id
                        join code in _sysCodeRepository.GetAll().Where(t => t.CodeId == "10") on toolingContent.UnitId equals code.Id
                        into codeData
                        from cd in codeData.DefaultIfEmpty()
                        join codeTool in _sysCodeRepository.GetAll().Where(t => t.CodeId == "11") on toolingContent.LifeStateId equals codeTool.Id
                        into codeToolData
                        from cdtd in codeToolData.DefaultIfEmpty()
                        join codeUser in _sysCodeRepository.GetAll().Where(t => t.CodeId == "12") on toolingContent.KeeperId equals codeUser.Id
                        into codeUserData
                        from cdud in codeUserData.DefaultIfEmpty()
                        join codeLevel in _sysCodeRepository.GetAll().Where(t => t.CodeId == "13") on toolingContent.LevelNo equals codeLevel.Id
                        into codeLevelData
                        from cdld in codeLevelData.DefaultIfEmpty()
                        join users in userData on toolingContent.CreatorUserId equals users.Id
                        select new ToolingContentDto
                        {
                            Id = toolingContent.Id,
                            ToolingName = toolingContent.ToolingName,
                            ToolingNo = toolingContent.ToolingNo,
                            ToolingTypeName = toolingNode.ToolingTypeName,
                            UnitId = cd.Id,
                            Unit = cd.Code,
                            ToolIsUseState = EnumTransfer.GetEnumName<ToolingIsUseState>((int)toolingContent.ToolIsUseStateEnum),
                            Modle = toolingContent.Modle,
                            LifeStateId = cdtd.Id,
                            LifeStateName = cdtd.Code,
                            Remark = toolingContent.Remark,
                            KeeperId = cdud.Id,
                            KeeperName = cdud.Code,
                            LevelNo = cdld.Code,
                            DrawingNo = toolingContent.DrawingNo,
                            CreateUserName = users.Surname +users.Name
                        };
            if (query != null)
            {
                try
                {
                    var toolingContentDataList = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
                    return new PagedResultDto<ToolingContentDto>(query.Count(), toolingContentDataList);
                }
                catch (Exception ex)
                {
                    throw new UserFriendlyException("系统内部错误,请重试或联系管理员");
                }
            }
            else
            {
                throw new UserFriendlyException("异常,请重试或联系管理员");
            }
        }
        /// <summary>
        /// 工装详细信息新增和修改接口，根据是否传输id判断
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreateOrUpdateMaterialsContent(ToolingEditContentDto toolingEditContentDto)
        {
            if (toolingEditContentDto.Id == Guid.Empty)
            {
                await CreateToolingContent(toolingEditContentDto);
            }
            else
            {
                await UpdateToolingContent(toolingEditContentDto);
            }
        }
        /// <summary>
        /// 增加工装详细信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task CreateToolingContent(ToolingEditContentDto toolingEditContentDto)
        {
            ToolingContent toolingContent = new ToolingContent()
            {
                ToolingNo = toolingEditContentDto.ToolingNo,
                ToolingName = toolingEditContentDto.ToolingName,
                ToolingTypeCode = toolingEditContentDto.ToolingTypeCode,
                ToolingNodeId = toolingEditContentDto.ToolingNodeId,
                UnitId = toolingEditContentDto.UnitId,
                ToolIsUseStateEnum = (ToolingIsUseState)toolingEditContentDto.ToolingIsUseState,
                Modle = toolingEditContentDto.Modle,
                LifeStateId = toolingEditContentDto.LifeStateId,
                KeeperId = toolingEditContentDto.KeeperId,
                LevelNo = toolingEditContentDto.LevelNo,
                DrawingNo = toolingEditContentDto.DrawingNo,
                Remark = toolingEditContentDto.Remark,
                PreviousVerifyTime = toolingEditContentDto.PreviousVerifyTime,
                CheckCycleTime = toolingEditContentDto.CheckCycleTime

            };
            await _toolingContentRepostory.InsertAsync(toolingContent);
        }

        /// <summary>
        /// 更新工装详细信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task UpdateToolingContent(ToolingEditContentDto toolingEditContentDto)
        {
            var toolingContentData = await _toolingContentRepostory.FirstOrDefaultAsync(c => c.Id == toolingEditContentDto.Id);
            if (toolingContentData != null)
            {
                var materialsEditContentNew = ObjectMapper.Map(toolingEditContentDto, toolingContentData);
                await _toolingContentRepostory.UpdateAsync(materialsEditContentNew);
            }
            else
            {
                throw new UserFriendlyException("该物料不存在");
            }
        }
        /// <summary>
        /// 删除工装细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteMaterialsContent(Guid id)
        {
            var materialsContentData = await _toolingContentRepostory.FirstOrDefaultAsync(x => x.Id == id);
            if (materialsContentData != null)
            {
                await _toolingContentRepostory.DeleteAsync(id);
            }
            else
            {
                throw new UserFriendlyException("没有找到对应工装的详细信息");

            }
        }
        /// <summary>
        /// 获取添加工装详细信息模态框的工装类型
        /// </summary>
        /// <returns></returns>
        public List<ToolingOtherDto> GetMaterialsType()
        {
            var queryToolsType = from queryToolNodeData in _toolingNodeRepostory.GetAll()
                                 join queryToolDesc in _toolingDescRepostory.GetAll() on queryToolNodeData.ParentCode equals
                                 queryToolDesc.Id
                                 select new ToolingOtherDto
                                 {
                                     label = queryToolNodeData.ToolingTypeName,
                                     value = queryToolNodeData.Id
                                 };
            if (queryToolsType.Count() > 0)
            {
                return queryToolsType.ToList();
            }
            return new List<ToolingOtherDto>();
        }
        /// <summary>
        /// 获取单位
        /// </summary>
        /// <returns></returns>
        public async Task<List<ToolingOtherDto>> GetCode()
        {
            var queryCode = from queryCodeData in _sysCodeRepository.GetAll().Where(t => t.CodeId == "10")
                            select new ToolingOtherDto
                            {
                                label = queryCodeData.Code,
                                value = queryCodeData.Id
                            };
            if (queryCode.Count() > 0)
            {
                return queryCode.ToList();
            }
            return new List<ToolingOtherDto>();
        }
        /// <summary>
        /// 获取寿命状态
        /// </summary>
        /// <returns></returns>
        public async Task<List<ToolingOtherDto>> GetLifeStateData()
        {
            var queryLifeStates = from queryLifeState in _sysCodeRepository.GetAll().Where(t => t.CodeId == "11")
                                  select new ToolingOtherDto
                                  {
                                      label = queryLifeState.Code,
                                      value = queryLifeState.Id
                                  };
            if (queryLifeStates.Count() > 0)
            {
                return queryLifeStates.ToList();
            }
            return new List<ToolingOtherDto>();
        }
        /// <summary>
        /// 获取保管员
        /// </summary>
        /// <returns></returns>
        public async Task<List<ToolingOtherDto>> GetKeeperNameData()
        {
            var queryKeeperNames = from queryKeeperName in _sysCodeRepository.GetAll().Where(t => t.CodeId == "12")
                                   select new ToolingOtherDto
                                   {
                                       label = queryKeeperName.Code,
                                       value = queryKeeperName.Id
                                   };
            if (queryKeeperNames.Count() > 0)
            {
                return queryKeeperNames.ToList();
            }
            return new List<ToolingOtherDto>();
        }
        /// <summary>
        /// 获取等级列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<ToolingOtherDto>> GetLevelsData()
        {
            var queryLevels = from queryLevelName in _sysCodeRepository.GetAll().Where(t => t.CodeId == "13")
                              select new ToolingOtherDto
                              {
                                  label = queryLevelName.Code,
                                  value = queryLevelName.Id
                              };
            if (queryLevels.Count() > 0)
            {
                return queryLevels.ToList();
            }
            return new List<ToolingOtherDto>();
        }
        /// <summary>
        /// 导出工装夹具主页内容
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> GetMaterialsContentToExcel(IList<ToolingContentDto> toolingsContentDtos)
        {
            List<ToolingContentDto> toolingsContents = new List<ToolingContentDto>();
            foreach (ToolingContentDto toolingContent in toolingsContentDtos)
            {
                var toolingsContentData = _toolingContentRepostory.FirstOrDefaultAsync(t => toolingContent.Id.ToString().Equals(t.Id)).Result;
                if (toolingsContentData != null)
                {
                    toolingsContents.Add(toolingContent);
                }
            }
            return _toolingsExprotToExcel.ExportToFile(toolingsContents);
        }

        /// <summary>
        /// 导入工装信息
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public string GetExcelToMaterialsContent(IFormFile file)

        {
            if (file == null)
            {
                throw new UserFriendlyException("没有找到有效文件");
            }
            StringBuilder errorMsg = new StringBuilder(); // 错误信息
                                                          // String fileName = file.FileName;
            List<ToolingContent> materialsContentsList = new List<ToolingContent>();
            // 单元格抬头
            // key：实体对象属性名称，可通过反射获取值
            // value：属性对应的中文注解
            Dictionary<string, string> cellheader = new Dictionary<string, string> {
                    { "ToolingNo", "工装编号"},
                    { "ToolingName", "工装名称"},
                    { "ToolingTypeName", "工装类别"},
                    { "Unit", "单位"},
                    { "ToolingIsUseState", "使用状态"},
                    { "Model", "规格型号"},
                    { "PreviousVerifyTime", "上次校验日期"},
                    { "CheckCycleTime", "校验周期/天"},
                    { "DrawingNo", "产品图号"},
                    { "LevelNo", "等级"},
                    { "LifeStateName", "寿命状态"},
                    { "KeeperName", "保管员"},
                    { "Remark", "备注"}
                };
            // 1.2解析文件，存放到一个List集合里
            List<ToolingContentDto> enlist = _toolingsImportToTable.GetExcelList<ToolingContentDto>(cellheader, file, out errorMsg);
            #region 校验
            #region 检测是否必填与值的有效性
            for (int i = 0; i < enlist.Count; i++)
            {
                ToolingContentDto en = enlist[i];
                string errorMsgStr = "第" + (i + 1) + "行数据检测异常：";
                bool isHaveNoInputValue = false; // 是否含有未输入项
                if (string.IsNullOrEmpty(en.ToolingNo))
                {
                    errorMsgStr += "工装编号列不能为空；";
                    isHaveNoInputValue = true;
                }
                if (string.IsNullOrEmpty(en.ToolingName))
                {
                    errorMsgStr += "工装名称不能为空；";
                    isHaveNoInputValue = true;
                }
                if (string.IsNullOrEmpty(en.ToolingTypeName))
                {
                    errorMsgStr += "工装类别不能为空；";
                    isHaveNoInputValue = true;
                }
                else
                {
                    int queryToolingType = _toolingNodeRepostory.Count(t => t.ToolingTypeName == en.ToolingTypeName);
                    if (queryToolingType == 0)
                    {
                        errorMsgStr += "工装类型名称与现有类型不符；";
                        isHaveNoInputValue = true;
                    }
                    int queryToolingContent = _toolingContentRepostory.Count(t => t.ToolingNo == en.ToolingNo && t.ToolingName == en.ToolingName);
                    if (queryToolingContent > 0)
                    {
                        errorMsgStr += "已存在该工装；";
                        isHaveNoInputValue = true;
                    }
                }
                if (string.IsNullOrEmpty(en.Unit))
                {
                    errorMsgStr += "物料单位列不能为空；";
                    isHaveNoInputValue = true;
                }
                if (isHaveNoInputValue) // 若必填项有值未填
                {
                    en.IsExcelVaildateOK = false;
                    errorMsg.AppendLine(errorMsgStr);
                }
            }
            #endregion

            #region 2.2检测Excel中是否有重复对象

            for (int i = 0; i < enlist.Count; i++)
            {
                ToolingContentDto enA = enlist[i];
                if (enA.IsExcelVaildateOK == false) // 上面验证不通过，不进行此步验证
                {
                    continue;
                }

                for (int j = i + 1; j < enlist.Count; j++)
                {
                    ToolingContentDto enB = enlist[j];
                    // 判断必填列是否全部重复
                    if (enA.ToolingNo == enB.ToolingNo)
                    {
                        enA.IsExcelVaildateOK = false;
                        enB.IsExcelVaildateOK = false;
                        errorMsg.AppendLine("第" + (i + 1) + "行与第" + (j + 1) + "行的必填列重复了");
                    }
                    // 判断必填列是否全部重复
                    if (enA.ToolingName == enB.ToolingName)
                    {
                        enA.IsExcelVaildateOK = false;
                        enB.IsExcelVaildateOK = false;
                        errorMsg.AppendLine("第" + (i + 1) + "行与第" + (j + 1) + "行的必填列重复了");
                    }
                }
            }
            #endregion
            #endregion
            #region 对数据进行持久化操作
            if (enlist.Count > 0 && errorMsg.Length == 0)
            {
                foreach (ToolingContentDto ms in enlist)
                {
                    #region 使用状态赋值
                    if (ms.ToolIsUseState.ToString() == ToolEnum.ToolingIsUseState.使用.ToString())
                    {
                        ms.ToolIsUseState = ToolEnum.ToolingIsUseState.使用.ToString();
                    }
                    else if (ms.ToolIsUseState.ToString() == ToolEnum.ToolingIsUseState.停用.ToString())
                    {
                        ms.ToolIsUseState = ToolEnum.ToolingIsUseState.停用.ToString();
                    }
                    #endregion
                    #region 工装类别赋值
                    var queryToolingType = _toolingNodeRepostory.FirstOrDefaultAsync(t => t.ToolingTypeName == ms.ToolingTypeName).Result;
                    ms.ToolingNodeId = queryToolingType.Id;
                    #endregion
                    #region 单位、等级、寿命状态、保管员赋值
                    //单位
                    var querySysCodesUnit = _sysCodeRepository.FirstOrDefaultAsync(t => t.Code == ms.Unit && t.CodeId == "10").Result;
                    //等级
                    var querySysCodesLevel = _sysCodeRepository.FirstOrDefaultAsync(t => t.Code == ms.LevelNo && t.CodeId == "13").Result;
                    //寿命状态
                    var querySysCodesLiftState = _sysCodeRepository.FirstOrDefaultAsync(t => t.Code == ms.LifeStateName && t.CodeId == "11").Result;
                    //保管员
                    var querySysCodesKeeper = _sysCodeRepository.FirstOrDefaultAsync(t => t.Code == ms.KeeperName && t.CodeId == "12").Result;
                    ms.UnitId = querySysCodesUnit.Id;
                    ms.LevelNoId = querySysCodesLevel.Id;
                    ms.LifeStateId = querySysCodesLiftState.Id;
                    ms.KeeperId = querySysCodesKeeper.Id;
                    #endregion
                    ToolingContent toolingContent = new ToolingContent()
                    {
                        ToolingNo = ms.ToolingNo,
                        ToolingName = ms.ToolingName,
                        ToolingTypeCode = queryToolingType.ToolingTypeCode,
                        ToolingNodeId = ms.ToolingNodeId,
                        UnitId = ms.UnitId,
                        ToolIsUseStateEnum = (ToolingIsUseState)EnumTransfer.GetEnumValue<ToolingIsUseState>(ms.ToolIsUseState.ToString()),
                        Modle = ms.Modle,
                        LifeStateId = ms.LifeStateId,
                        KeeperId = ms.KeeperId,
                        LevelNo = ms.LevelNoId,
                        DrawingNo = ms.DrawingNo,
                        Remark = ms.Remark,
                        PreviousVerifyTime = ms.PreviousVerifyTime,
                        CheckCycleTime = ms.CheckCycleTime
                    };
                    materialsContentsList.Add(toolingContent);
                }
                if (materialsContentsList.Count() > 0)
                {
                    foreach (ToolingContent materialsContent in materialsContentsList)
                    {
                        _toolingContentRepostory.InsertAsync(materialsContent);
                    }
                }
            }
            #endregion
            if (errorMsg.Length > 0)
            {
                return errorMsg.ToString();
            }
            return "success";
        }
    }
}
